// @flow
import React from 'react'
import { DatePicker, Form, Input, Select, Button, message } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './Home.css'
const { RangePicker } = DatePicker
import { connect } from 'react-redux'

type Props = {
  userId: string,
  form: Object,
  history: Object
}

const FormItem = Form.Item
const Option = Select.Option

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type States = {
  deviceData: Array<any>,
  loading: boolean
}
class MaintenanceAdd extends React.Component {
  props: Props
  state: States
  goBack: Function
  getCustomers: Function
  getCustomerDeviceData: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      deviceData: [],
      loading: false,
      customers: [{}]
    }

    this.goBack = this.goBack.bind(this)
    this.getCustomers = this.getCustomers.bind(this)
    this.getCustomerDeviceData = this.getCustomerDeviceData.bind(this)
  }

  goBack () {
    const { history } = this.props
    history.push('/business/maintenance')
  }

  /**
   * 提交表单
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      const rangeTime = fieldsValue.rangeTime
      const values = {
        ...fieldsValue,
        'componentId': 0, // 后台设定的必须传的值，但没有实际意义
        'startTime': rangeTime[0].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
        'endTime': rangeTime[1].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
      }
      universalFetch(`${__SERVICE_API__}device/events/maintenances`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(values)
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('维修记录添加成功')
        this.props.history.push('/business/maintenance')
        this.setState({
          loading: false
        })
      })
      .catch((error) => {
        console.error(error)
        this.setState({
          loading: false
        })
        message.error('维修记录添加失败： ' + err.message, 10)
      })
    })
  }
  componentDidMount () {
    this.getCustomers()
  }
  getCustomers () {
    universalFetch(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageSize=200000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.setState({
          customers: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getCustomerDeviceData (val) {
    universalFetch(`${__SERVICE_API__}device/customers/${val}/devices`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.props.form.resetFields(['deviceId'])
        this.setState({
          deviceData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { loading, deviceData, customers } = this.state
    return (
      <div className={styles['main']}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label='客户'>
            {getFieldDecorator('customer', {
              rules: [
                { required: true, message: '请选择客户' }
              ]
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择客户' onChange={this.getCustomerDeviceData}>
                {
                  customers.map((d, i) => {
                    return <Option key={i} value={d.id}>{d.name}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='设备'>
            {getFieldDecorator('deviceId', {
              rules: [
                { required: true, message: '请选择设备' }
              ]
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择设备' >
                {
                  deviceData.map((d, i) => {
                    return <Option key={i} value={d.id}>{d.name}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='维修名称'>
            {getFieldDecorator('eventName', {
              rules: [
                { required: true, message: '请输入维修名称', whitespace: true }
              ]
            })(
              <Input placeholder='请输入维修名称' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='维修类型' hasFeedback>
            {getFieldDecorator('eventType', {
              rules: [
                { required: true, message: '请输入维修类型', whitespace: true }
              ]
            })(
              <Input placeholder='请输入维修类型' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='起止日期'>
            {getFieldDecorator('rangeTime', {
              rules: [
                { required: true, message: '请选择起止日期' }
              ]
            })(
              <RangePicker size='default' />
            )}
          </FormItem>
          {
            // <FormItem {...formItemLayout} label='开始时间'>
            //   {getFieldDecorator('startTime', {
            //     rules: [
            //       { required: true, message: '请选择开始时间' }
            //     ]
            //   })(
            //     <DatePicker placeholder='请选择开始时间' />
            //   )}
            // </FormItem>
            // <FormItem {...formItemLayout} label='结束时间'>
            //   {getFieldDecorator('endTime', {
            //     rules: [
            //       { required: true, message: '请选择结束时间' }
            //     ]
            //   })(
            //     <DatePicker placeholder='请选择结束时间' />
            //   )}
            // </FormItem>
          }
          <FormItem {...formItemLayout} label='负责人'>
            {getFieldDecorator('owner', {
              rules: [
                { required: true, message: '请输入负责人', whitespace: true }
              ]
            })(
              <Input placeholder='请输入负责人' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='处理方法'>
            {
              getFieldDecorator('dealMethod')(
                <Input placeholder='请输入处理方法' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='状态'>
            {
              getFieldDecorator('status')(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择状态'>
                  <Option key='1' value='已解决'>已解决</Option>
                  <Option key='2' value='未解决'>未解决</Option>
                  <Option key='3' value='生成工单'>生成工单</Option>
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='描述' hasFeedback>
            {getFieldDecorator('detail', {})(
              <Input placeholder='请填写描述' />
            )}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary' htmlType='submit' size='large'
              loading={loading}
              >保存</Button>
            <Button style={{ marginLeft: '20px' }}
              onClick={this.goBack}
              >返回</Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Form.create()(MaintenanceAdd))
